package com.example.demo.controller;

import com.example.demo.entity.Stu;
import com.example.demo.service.LogService;
import com.example.demo.service.StuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/stu")
public class StuController {
    @Autowired
    private StuService stuService;

    //注入事务的对象
    @Autowired
    private DataSourceTransactionManager transactionManager;

    //设置事务的属性
    @Autowired
    private TransactionDefinition transactionDefinition;

    //注入日志service的对象
    @Autowired
    private LogService logService;

    @RequestMapping("/add")
    public int add(Stu stu){
        //非空校验
        if (stu == null || stu.getId() ==null
                || stu.getName() == null
                || stu.getName() == null) {
            return 0;
        }
        //1.开启事务(下面语句表示得到并开启事务)
        TransactionStatus transactionStatus =
                transactionManager.getTransaction(transactionDefinition);

        int res = stuService.add(stu);
        System.out.println(res);

//        //2.回滚事务
//        transactionManager.rollback(transactionStatus);
        //提交事务
        transactionManager.commit(transactionStatus);
        return res;

    }

    //声明式的自动提交事务
    @Transactional(propagation = Propagation.REQUIRED)
    @RequestMapping("/add2")
    public int add2(Stu stu){
        //非空校验
        if (stu == null || stu.getId() ==null
                || stu.getName() == null
                || stu.getName() == null) {
            return 0;
        }
        //先添加用户
        int res = stuService.add(stu);

        if (res > 0){
            logService.add();
        }
//        try {
//            int num = 100/0;
//        } catch (Exception e) {
////            throw e;
////            e.printStackTrace();
//            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//        }
        return res;
    }
}
